<script setup>
import { ref, onMounted, computed } from 'vue'
import api from '@/utils/api'
import Toast from '@/components/Toast.vue'
import { showToast } from '@/utils/toast'
import * as XLSX from 'xlsx'

// 账单数据
const bills = ref([]) // 存储账单列表数据
const loading = ref(false) // 加载状态标识
const isBillListVisible = ref(false) // 控制账单列表显示状态

// 预算数据
const budgets = ref([]) // 存储预算列表数据
const loadingBudget = ref(false) // 预算加载状态标识
const isBudgetVisible = ref(true) // 控制预算列表显示状态

// 筛选条件
const filter = ref({
  bill_type: '', // 账单类型
  type: '', // 支付类型
  payment_status: '', // 支付状态
  payment_method: '', // 支付方式
  member: '' // 家庭成员
})

// 分页状态
const current_page = ref(1) // 当前页码
const page_size = ref(10) // 每页显示条数
const totalBills = ref(0) // 总账单数

// 计算总页数
const totalPages = computed(() => {
  return Math.ceil(totalBills.value / page_size.value)
})

// 家庭成员列表
const familyMembers = ref([]) // 存储家庭成员数据

// 添加排序相关的状态
const sortConfig = ref({
  amount: '', // 金额排序：'asc' 或 'desc'
  due_date: '', // 记录日期排序
  created_date: '' // 创建时间排序
})

// 计算总预算和实际支出
const totalBudget = computed(() => budgets.value.reduce((sum, budget) => sum + budget.total_amount, 0))
const totalActualExpense = computed(() => budgets.value.reduce((sum, budget) => sum + budget.total_actual_expense, 0))

// 动态计算实际支出的颜色
const actualExpenseColor = computed(() => {
  return totalActualExpense.value > totalBudget.value ? '#f56c6c' : '#67c23a'
})

// 格式化金额
const formatAmount = (amount) => {
  return Number(amount).toFixed(2)
}

// 用户管理相关状态
const showUserManagementModal = ref(false) // 控制用户管理弹窗显示
const userPermissions = ref(0) // 当前用户权限
const showDeleteFamilyConfirm = ref(false) // 删除家庭确认对话框

// 当前用户ID
const currentUserId = ref(null) // 存储当前用户ID

// 用户信息相关状态
const hasFamily = ref(false) // 是否已加入家庭
const showCreateFamilyModal = ref(false) // 控制创建家庭弹窗显示
const showJoinFamilyModal = ref(false) // 控制加入家庭弹窗显示
const inviteCode = ref('') // 邀请码
const familyName = ref('') // 家庭名称
const currentFamilyName = ref('') // 当前家庭名称

// 获取用户信息
const getUserInfo = async () => {
  try {
    const response = await api.get('/api/check_family')
    if (response.data.code === 0) {
      const { user_id, family_type, family_permissions, family_name, invite_code } = response.data.data
      currentUserId.value = user_id
      hasFamily.value = family_type > 0
      currentFamilyName.value = family_name || ''
      userPermissions.value = parseInt(family_permissions)
      inviteCode.value = invite_code || ''
      if (!hasFamily.value) {
        // 如果没有加入家庭，不加载其他数据
        return
      }
      // 如果已加入家庭，继续加载其他数据
      await getFamilyMembers()
      await getBudgets()
      await fetchBills()
    }
  } catch (error) {
    showToast('获取用户信息失败', 'error')
  }
}

// 创建家庭
const createFamily = async () => {
  if (!familyName.value.trim()) {
    showToast('请输入家庭名称', 'warning')
    return
  }
  try {
    const response = await api.post('/api/create_family', {
      family_name: familyName.value
    })
    if (response.data.code === 0) {
      showToast('创建成功', 'success')
      showCreateFamilyModal.value = false
      familyName.value = ''
      // 重新获取用户信息
      await getUserInfo()
    } else {
      showToast(response.data.message || '创建失败', 'error')
    }
  } catch (error) {
    showToast('创建失败', 'error')
  }
}

// 使用邀请码加入家庭
const joinFamily = async () => {
  if (!inviteCode.value.trim()) {
    showToast('请输入邀请码', 'warning')
    return
  }
  try {
    const response = await api.post('/api/join_family', {
      invite_code: inviteCode.value
    })
    if (response.data.code === 0) {
      showToast('发送请求成功', 'success')
      showJoinFamilyModal.value = false
      inviteCode.value = ''
      // 重新获取用户信息
      await getUserInfo()
    } else {
      showToast(response.data.message || '发送请求失败', 'error')
    }
  } catch (error) {
    showToast('发送请求失败', 'error')
  }
}

// 设置管理员
const setFamilyAdmin = async (userId, isPromote) => {
  try {
    const response = await api.post('/api/set_family_admin', {
      user_id: userId,
      is_promote: isPromote
    })
    if (response.data.code === 0) {
      showToast(isPromote ? '升级成功' : '降级成功', 'success')
      await getFamilyMembers()
    } else {
      showToast(response.data.message || (isPromote ? '升级失败' : '降级失败'), 'error')
    }
  } catch (error) {
    showToast(isPromote ? '升级失败' : '降级失败', 'error')
  }
}

// 移出家庭成员
const removeFamilyMember = async (memberId) => {
  try {
    const response = await api.post('/api/remove_family_member', {
      user_id: memberId
    })
    if (response.data.code === 0) {
      showToast('退出家庭成功', 'success')
      // 3秒后刷新页面
      setTimeout(() => {
        window.location.reload()
      }, 2000)
    } else {
      showToast(response.data.message || '退出失败', 'error')
    }
  } catch (error) {
    showToast('退出失败', 'error')
  }
}

// 获取权限文本和样式
const getPermissionInfo = (permission) => {
  switch (permission) {
    case 0:
      return {
        text: '创建者',
        class: 'creator-tag'
      }
    case 1:
      return {
        text: '管理员',
        class: 'admin-tag'
      }
    case 2:
      return {
        text: '成员',
        class: 'member-tag'
      }
    default:
      return {
        text: '未知',
        class: ''
      }
  }
}

// 获取家庭成员列表
const getFamilyMembers = async () => {
  try {
    const response = await api.get('/api/get_family_members')
    if (response.data.code === 0) {
      familyMembers.value = response.data.data || []
    }
  } catch (error) {
    showToast('获取家庭成员列表失败', 'error')
  }
}

// 应用筛选
const applyFilter = () => {
  fetchBills()
}

// 重置筛选
const resetFilter = () => {
  filter.value = {
    bill_type: '',
    type: '',
    payment_status: '',
    payment_method: '',
    member: ''
  }
  fetchBills()
}

// 获取账单列表
const fetchBills = async () => {
  loading.value = true
  try {
    const response = await api.get('/api/get_family_bills', {
      params: {
        bill_type: filter.value.bill_type || '',
        payment_status: filter.value.payment_status === '' ? null : Number(filter.value.payment_status),
        type: filter.value.type === '' ? null : Number(filter.value.type),
        payment_method: filter.value.payment_method || '',
        member: filter.value.member || '',
        current_page: current_page.value,
        page_size: page_size.value
      }
    })
    bills.value = response.data.data
    totalBills.value = response.data.total
  } catch (error) {
    showToast('获取账单失败', 'error')
  } finally {
    loading.value = false
  }
}

// 更新分页
const handlePageChange = (page) => {
  current_page.value = page
  fetchBills()
}

// 处理排序
const handleSort = (field) => {
  if (!sortConfig.value[field]) {
    sortConfig.value[field] = 'desc'
  } else if (sortConfig.value[field] === 'desc') {
    sortConfig.value[field] = 'asc'
  } else {
    sortConfig.value[field] = 'desc'
  }
  
  Object.keys(sortConfig.value).forEach(key => {
    if (key !== field) {
      sortConfig.value[key] = ''
    }
  }) 
  
  bills.value.sort((a, b) => {
    let aValue = a[field]
    let bValue = b[field]
    
    if (field === 'amount') {
      aValue = parseFloat(aValue)
      bValue = parseFloat(bValue)
    }
    
    if (field === 'due_date' || field === 'created_date') {
      aValue = new Date(aValue).getTime()
      bValue = new Date(bValue).getTime()
    }
    
    if (aValue === bValue) {
      return sortConfig.value[field] === 'asc' ? 1 : -1
    }
    
    return sortConfig.value[field] === 'asc' 
      ? (aValue > bValue ? 1 : -1)
      : (aValue < bValue ? 1 : -1)
  })
}

// 获取预算列表
const getBudgets = async () => {
  loadingBudget.value = true
  try {
    const response = await api.get('/api/get_family_budgets')
    if (response.data.code === 0) {
      budgets.value = response.data.data || []
    }
  } catch (error) {
    showToast('获取预算列表失败', 'error')
  } finally {
    loadingBudget.value = false
  }
}

// 消息相关状态
const showMessageModal = ref(false) // 控制消息弹窗显示
const newMessage = ref('') // 新消息内容

// 发送消息
const sendMessage = async () => {
  if (!newMessage.value.trim()) {
    showToast('请输入消息内容', 'warning')
    return
  }
  
  try {
    const response = await api.post('/api/send_family_message', {
      message: newMessage.value
    })
    if (response.data.code === 0) {
      showToast('发送成功', 'success')
      newMessage.value = ''
      showMessageModal.value = false
    } else {
      showToast(response.data.message || '发送失败', 'error')
    }
  } catch (error) {
    showToast('发送失败', 'error')
  }
}

// 格式化时间
const formatDate = (dateStr) => {
  const date = new Date(dateStr)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 在 script setup 部分添加新的响应式变量
const showInviteModal = ref(false) // 控制邀请弹窗显示
const invitePhone = ref('') // 邀请手机号
const searchedUser = ref(null) // 搜索到的用户信息
const isSearching = ref(false) // 搜索状态

// 搜索用户函数
const searchUser = async () => {
  if (!invitePhone.value) return
  
  // 只在手机号长度为11时进行验证
  if (invitePhone.value.length !== 11) {
    searchedUser.value = null
    return
  }
  
  isSearching.value = true
  try {
    const response = await api.post('/api/validate_phone', {
      phone: invitePhone.value
    })
    
    if (response.data.code === 0) {
      searchedUser.value = response.data.data
    } else {
      searchedUser.value = null
      showToast(response.data.message || '该用户不可被邀请', 'warning')
    }
  } catch (error) {
    searchedUser.value = null
    showToast('验证手机号失败', 'error')
  } finally {
    isSearching.value = false
  }
}

// 发送邀请函数
const sendInvite = async () => {
  if (!searchedUser.value) return
  
  try {
    const response = await api.post('/api/send_invite', {
      phone: invitePhone.value
    })
    
    if (response.data.code === 0) {
      showToast('邀请发送成功', 'success')
      showInviteModal.value = false
      invitePhone.value = ''
      searchedUser.value = null
    } else {
      showToast(response.data.message || '邀请发送失败', 'error')
    }
  } catch (error) {
    showToast('邀请发送失败', 'error')
  }
}

// 删除家庭
const deleteFamily = async () => {
  try {
    const response = await api.post('/api/delete_family')
    if (response.data.code === 0) {
      showToast('删除成功', 'success')
      showDeleteFamilyConfirm.value = false
      showUserManagementModal.value = false
      // 重新获取用户信息
      await getUserInfo()
    } else {
      showToast(response.data.message || '删除失败', 'error')
    }
  } catch (error) {
    showToast('删除失败', 'error')
  }
}

// 关闭邀请模态框
const closeInviteModal = () => {
  showInviteModal.value = false
  invitePhone.value = ''
  searchedUser.value = null
}

// 导出Excel
const exportToExcel = () => {
  try {
    // 准备导出数据
    const exportData = bills.value.map(bill => ({
      '账单类型': bill.bill_type,
      '金额': bill.amount,
      '类型': bill.type === 1 ? '收入' : '支出',
      '支付状态': bill.type === 0 ? (bill.payment_status === 1 ? '已支付' : bill.payment_status === 0 ? '未支付' : '') : '',
      '支付方式': bill.payment_method || '',
      '记录日期': bill.due_date || '',
      '备注': bill.description || '',
      '创建时间': bill.created_date,
      '所属成员': bill.username
    }))

    // 创建工作簿
    const wb = XLSX.utils.book_new()
    const ws = XLSX.utils.json_to_sheet(exportData)

    // 设置列宽
    const colWidths = [
      { wch: 15 }, // 账单类型
      { wch: 10 }, // 金额
      { wch: 10 }, // 类型
      { wch: 10 }, // 支付状态
      { wch: 15 }, // 支付方式
      { wch: 15 }, // 记录日期
      { wch: 20 }, // 备注
      { wch: 20 }, // 创建时间
      { wch: 15 }  // 所属成员
    ]
    ws['!cols'] = colWidths

    // 添加工作表到工作簿
    XLSX.utils.book_append_sheet(wb, ws, '家庭账单')

    // 导出文件
    const fileName = `家庭账单_${new Date().toLocaleDateString()}.xlsx`
    XLSX.writeFile(wb, fileName)
    
    showToast('导出成功', 'success')
  } catch (error) {
    console.error('导出失败:', error)
    showToast('导出失败', 'error')
  }
}

onMounted(async () => {
  await getUserInfo()
})
</script>

<template>
  <div class="family-container">
    <Toast />
    <!-- 未加入家庭时显示的界面 -->
    <div v-if="!hasFamily" class="no-family-container">
      <div class="welcome-text">
        <h2>欢迎使用家庭财务管理系统</h2>
        <p>开始使用前，请先创建或加入一个家庭</p>
      </div>
      <div class="action-buttons">
        <div class="action-card" @click="showCreateFamilyModal = true">
          <div class="card-icon">
            <i class="fas fa-home"></i>
          </div>
          <h3>创建家庭</h3>
          <p>创建一个新的家庭，成为家庭创建者</p>
        </div>
        <div class="action-card" @click="showJoinFamilyModal = true">
          <div class="card-icon">
            <i class="fas fa-users"></i>
          </div>
          <h3>加入家庭</h3>
          <p>使用邀请码加入已有的家庭</p>
        </div>
      </div>
    </div>

    <!-- 已加入家庭时显示的原有内容 -->
    <div v-else class="family-content">
      <!-- 家庭名称和消息按钮 -->
      <div class="header-container">
        <div class="family-info">
          <div class="family-name">
            {{ currentFamilyName }}
            <span class="invite_code">邀请码：{{inviteCode}}</span>
          </div>
        </div>
        <div class="action-buttons">
          <button class="action-btn message-btn" @click="showMessageModal = true">
            <i class="fas fa-comment"></i>
            发送消息
          </button>
          <button class="action-btn user-btn" @click="showUserManagementModal = true">
            <i class="fas fa-users"></i>
            用户管理
          </button>
        </div>
      </div>

      <!-- 消息发送弹窗 -->
      <div v-if="showMessageModal" class="message-modal">
        <div class="message-modal-content">
          <div class="message-modal-header">
            <h3>发送家庭消息</h3>
            <button class="close-btn" @click="showMessageModal = false">×</button>
          </div>
          
          <div class="message-input-container">
            <textarea 
              v-model="newMessage"
              placeholder="输入要发送给家庭成员的消息..."
              class="message-textarea"
            ></textarea>
          </div>

          <div class="message-actions">
            <button @click="showMessageModal = false" class="cancel-btn">取消</button>
            <button @click="sendMessage" class="send-btn">发送</button>
          </div>
        </div>
      </div>

      <!-- 用户管理弹窗 -->
      <div v-if="showUserManagementModal" class="message-modal">
        <div class="message-modal-content">
          <div class="message-modal-header">
            <h3>家庭成员管理</h3>
            <button class="close-btn" @click="showUserManagementModal = false">×</button>
          </div>
          
          <div class="user-management-content">
            <div v-for="member in familyMembers" :key="member.id" class="member-item">
              <div class="member-info">
                <span class="member-name">{{ member.username }}</span>
                <span :class="['permission-tag', getPermissionInfo(member.family_permissions).class]">
                  {{ getPermissionInfo(member.family_permissions).text }}
                </span>
              </div>
              <div v-if="member.id === currentUserId" class="member-actions">
                  <button 
                    v-if="member.family_permissions > 0"
                    @click="removeFamilyMember(member.id)"
                    class="action-btn remove-btn"
                  >
                    退出家庭
                  </button>
              </div>
              <div v-else class="member-actions">
                <template v-if="userPermissions === 0">
                  <button 
                    v-if="member.family_permissions === 2"
                    @click="setFamilyAdmin(member.id, true)"
                    class="action-btn promote-btn"
                  >
                    升级为管理员
                  </button>
                  <button 
                    v-if="member.family_permissions === 1"
                    @click="setFamilyAdmin(member.id, false)"
                    class="action-btn demote-btn"
                  >
                    降级为普通成员
                  </button>
                  <button 
                    v-if="member.family_permissions >= 1"
                    @click="removeFamilyMember(member.id)"
                    class="action-btn remove-btn"
                  >
                    移出家庭
                  </button>
                </template>
                <template v-else-if="userPermissions === 1">
                  <button 
                    v-if="member.family_permissions === 2"
                    @click="removeFamilyMember(member.id)"
                    class="action-btn remove-btn"
                  >
                    移出家庭
                  </button>
                </template>
              </div>
            </div>
          </div>

          <div class="message-actions">
            <button 
              v-if="userPermissions === 0"
              @click="showDeleteFamilyConfirm = true" 
              class="delete-family-btn"
            >
              删除家庭
            </button>
            <button 
              v-if="userPermissions === 0 || userPermissions === 1"
              @click="showInviteModal = true" 
              class="invite-btn"
            >
              邀请新成员
            </button>
            <button @click="showUserManagementModal = false" class="cancel-btn">关闭</button>
          </div>
        </div>
      </div>

      <!-- 删除家庭确认弹窗 -->
      <div v-if="showDeleteFamilyConfirm" class="message-modal">
        <div class="message-modal-content" style="width: 400px;">
          <div class="message-modal-header">
            <h3>确认删除家庭</h3>
            <button class="close-btn" @click="showDeleteFamilyConfirm = false">×</button>
          </div>
          <div class="modal-body">
            <p class="warning-text">警告：删除家庭后，所有成员将退出该家庭，此操作不可恢复！</p>
          </div>
          <div class="message-actions">
            <button @click="showDeleteFamilyConfirm = false" class="cancel-btn">取消</button>
            <button @click="deleteFamily" class="delete-btn">确认删除</button>
          </div>
        </div>
      </div>

      <!-- 邀请用户弹窗 -->
      <div v-if="showInviteModal && userPermissions <= 1" class="message-modal">
        <div class="message-modal-content" style="width: 320px;">
          <div class="message-modal-header">
            <h3>邀请新成员</h3>
            <button class="close-btn" @click="closeInviteModal">×</button>
          </div>
          
          <div class="invite-content">
            <div class="phone-input-group">
              <input 
                v-model="invitePhone"
                type="text"
                placeholder="请输入手机号"
                class="phone-input"
                @input="searchUser"
              />
            </div>
            
            <div v-if="isSearching" class="searching-status">
              搜索中...
            </div>
            
            <div v-else-if="searchedUser" class="searched-user">
              <div class="user-info">
                <span class="label">用户名：</span>
                <span class="value">{{ searchedUser.username }}</span>
              </div>
              <div class="user-info">
                <span class="label">手机号：</span>
                <span class="value">{{ searchedUser.phone }}</span>
              </div>
            </div>
          </div>

          <div class="message-actions">
            <button @click="closeInviteModal" class="cancel-btn">关闭</button>
            <button 
              @click="sendInvite" 
              class="send-btn"
              :disabled="!searchedUser"
            >
              发送邀请
            </button>
          </div>
        </div>
      </div>

      <!-- 预算管理部分 -->
      <div class="section">
        <h2 @click="isBudgetVisible = !isBudgetVisible" class="clickable">
          家庭预算
          <button class="toggle-btn">
            {{ isBudgetVisible ? '▼' : '▲' }}
          </button>
        </h2>

        <div v-show="isBudgetVisible">
          <!-- 总预算与实际支出卡片 -->
          <div class="budget-summary-card">
            <div class="summary-item total-budget">
              <div class="label">总预算</div>
              <div class="amount">¥{{ formatAmount(totalBudget) }}</div>
            </div>
            <div class="summary-item actual-expense">
              <div class="label">实际支出</div>
              <div class="amount" :style="{ color: actualExpenseColor }">
                ¥{{ formatAmount(totalActualExpense) }}
              </div>
            </div>
          </div>

          <!-- 预算列表 -->
          <div class="budget-list">
            <div v-if="loadingBudget" class="loading">加载中...</div>
            <div v-else-if="budgets.length === 0" class="empty">暂无预算记录</div>
            <div v-else class="budget-items">
              <div v-for="budget in budgets" :key="budget.category" class="budget-item">
                <div class="budget-info">
                  <div class="category">{{ budget.category }}</div>
                  <div class="amounts">
                    <span class="amount">预算: ¥{{ formatAmount(budget.total_amount) }}</span>
                    <span 
                      class="actual-amount" 
                      :style="{ color: budget.total_actual_expense > budget.total_amount ? '#f56c6c' : '#67c23a' }"
                    >
                      实际: ¥{{ formatAmount(budget.total_actual_expense) }}
                    </span>
                    <span class="percentage">
                      ({{ ((budget.total_actual_expense / budget.total_amount) * 100).toFixed(2) }}%)
                    </span>
                  </div>
                  <div class="progress-bar">
                    <div 
                      class="progress" 
                      :style="{ 
                        width: Math.min((budget.total_actual_expense / budget.total_amount) * 100, 100) + '%',
                        backgroundColor: budget.total_actual_expense > budget.total_amount ? '#f56c6c' : '#67c23a'
                      }"
                    ></div>
                  </div>
                  <div class="budget-users">
                    <div 
                      v-for="user in budget.users" 
                      :key="user.username" 
                      class="user-budget"
                    >
                      <span 
                        class="status-dot" 
                        :class="{ 'over-budget': user.is_over_budget }"
                      ></span>
                      <span class="username">{{ user.username }}</span>
                      <span class="user-amount">
                        (预算: ¥{{ formatAmount(user.amount) }} / 实际: ¥{{ formatAmount(user.actual_expense) }})
                      </span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 账单管理部分 -->
      <div class="section">
        <h2 @click="isBillListVisible = !isBillListVisible" class="clickable">
          家庭账单
          <button class="toggle-btn">
            {{ isBillListVisible ? '▼' : '▲' }}
          </button>
        </h2>

        <div v-show="isBillListVisible">
          <!-- 搜索和筛选区域 -->
          <div class="search-section">
            <div class="search-inputs">
              <div class="input-group">
                <input 
                  type="text" 
                  v-model="filter.bill_type" 
                  placeholder="请输入账单类型"
                  class="search-input"
                >
              </div>
              <div class="input-group">
                <select v-model="filter.type" class="type-select">
                  <option value="">全部类型</option>
                  <option value="0">支出</option>
                  <option value="1">收入</option>
                </select>
              </div>
              <div class="input-group" v-if="filter.type !== '1'">
                <select v-model="filter.payment_status" class="type-select">
                  <option value="">全部状态</option>
                  <option value="0">未支付</option>
                  <option value="1">已支付</option>
                </select>
              </div>
              <div class="input-group">
                <select v-model="filter.member" class="type-select">
                  <option value="">全部成员</option>
                  <option 
                    v-for="member in familyMembers" 
                    :key="member.id" 
                    :value="member.id"
                  >
                    {{ member.username }}
                  </option>
                </select>
              </div>
              <div class="button-group">
                <button @click="applyFilter" class="search-btn">
                  <i class="fas fa-search"></i>
                  查询
                </button>
                <button @click="resetFilter" class="reset-btn">
                  <i class="fas fa-redo"></i>
                  重置
                </button>
                <button @click="exportToExcel" class="export-btn">
                  <i class="fas fa-file-excel"></i>
                  导出Excel
                </button>
              </div>
            </div>
          </div>

          <!-- 账单列表 -->
          <div class="table-container">
            <table class="bill-table" v-if="!loading && bills.length > 0">
              <thead>
                <tr>
                  <th>账单类型</th>
                  <th @click="handleSort('amount')" class="sortable">
                    金额
                    <span :class="['sort-icon', sortConfig.amount]">
                      <svg viewBox="0 0 1024 1024" width="14" height="14">
                        <path d="M858.9 689L530.5 308.2c-9.4-10.9-27.5-10.9-37 0L165.1 689c-12.2 14.2-1.2 35 18.5 35h656.8c19.7 0 30.7-20.8 18.5-35z" fill="currentColor"/>
                      </svg>
                    </span>
                  </th>
                  <th>支付/收款</th>
                  <th>支付状态</th>
                  <th>支付方式</th>
                  <th @click="handleSort('due_date')" class="sortable">
                    记录日期
                    <span :class="['sort-icon', sortConfig.due_date]">
                      <svg viewBox="0 0 1024 1024" width="14" height="14">
                        <path d="M858.9 689L530.5 308.2c-9.4-10.9-27.5-10.9-37 0L165.1 689c-12.2 14.2-1.2 35 18.5 35h656.8c19.7 0 30.7-20.8 18.5-35z" fill="currentColor"/>
                      </svg>
                    </span>
                  </th>
                  <th>备注</th>
                  <th @click="handleSort('created_date')" class="sortable">
                    创建时间
                    <span :class="['sort-icon', sortConfig.created_date]">
                      <svg viewBox="0 0 1024 1024" width="14" height="14">
                        <path d="M858.9 689L530.5 308.2c-9.4-10.9-27.5-10.9-37 0L165.1 689c-12.2 14.2-1.2 35 18.5 35h656.8c19.7 0 30.7-20.8 18.5-35z" fill="currentColor"/>
                      </svg>
                    </span>
                  </th>
                  <th>所属成员</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="bill in bills" :key="bill.bill_id">
                  <td>{{ bill.bill_type }}</td>
                  <td class="amount" :class="bill.type === 1 ? 'income' : 'expense'">
                    {{ bill.type === 1 ? '+' : '-' }}¥{{ bill.amount }}
                  </td>
                  <td>{{ bill.type === 1 ? '收入' : '支出' }}</td>
                  <td>
                    <span v-if="bill.type === 0" :class="['status-tag', bill.payment_status === 1 ? 'status-paid' : 'status-unpaid']">
                      {{ bill.payment_status === 1 ? '已支付' : bill.payment_status === 0 ? '未支付' : '' }}
                    </span>
                    <span v-else></span>
                  </td>
                  <td>{{ bill.payment_method || '' }}</td>
                  <td>{{ bill.due_date || '' }}</td>
                  <td>{{ bill.description || '' }}</td>
                  <td>{{ bill.created_date }}</td>
                  <td>{{ bill.username }}</td>
                </tr>
              </tbody>
            </table>
            
            <div v-if="loading" class="empty-state">
              <i class="fas fa-spinner fa-spin"></i>
              加载中...
            </div>
            
            <div v-if="!loading && bills.length === 0" class="empty-state">
              <i class="fas fa-inbox"></i>
              暂无账单记录
            </div>
          </div>

          <!-- 分页 -->
          <div class="pagination">
            <span class="total-records">共 {{ totalBills }} 条</span>
            <select v-model="page_size" @change="fetchBills" class="page-size-select">
              <option value="10">10条/页</option>
              <option value="20">20条/页</option>
              <option value="50">50条/页</option>
              <option value="100">100条/页</option>
            </select>
            <button @click="handlePageChange(current_page - 1)" :disabled="current_page === 1" class="page-btn">上一页</button>

            <div class="page-numbers">
              <button 
                v-for="page in totalPages" 
                :key="page" 
                @click="handlePageChange(page)" 
                :class="{'active': page === current_page}"
              >
                {{ page }}
              </button>
            </div>

            <button @click="handlePageChange(current_page + 1)" :disabled="current_page * page_size >= totalBills" class="page-btn">下一页</button>
          </div>
        </div>
      </div>
    </div>

    <!-- 创建家庭弹窗 -->
    <div v-if="showCreateFamilyModal" class="message-modal">
      <div class="message-modal-content" style="width: 400px;">
        <div class="message-modal-header">
          <h3>创建家庭</h3>
          <button class="close-btn" @click="showCreateFamilyModal = false">×</button>
        </div>
        <div class="modal-body">
          <div class="input-group">
            <input 
              v-model="familyName"
              type="text"
              placeholder="请输入家庭名称"
              class="form-input"
            />
          </div>
        </div>
        <div class="message-actions">
          <button @click="showCreateFamilyModal = false" class="cancel-btn">取消</button>
          <button @click="createFamily" class="confirm-btn">创建</button>
        </div>
      </div>
    </div>

    <!-- 加入家庭弹窗 -->
    <div v-if="showJoinFamilyModal" class="message-modal">
      <div class="message-modal-content" style="width: 400px;">
        <div class="message-modal-header">
          <h3>加入家庭</h3>
          <button class="close-btn" @click="showJoinFamilyModal = false">×</button>
        </div>
        <div class="modal-body">
          <div class="input-group">
            <input 
              v-model="inviteCode"
              type="text"
              placeholder="请输入邀请码"
              class="form-input"
            />
          </div>
        </div>
        <div class="message-actions">
          <button @click="showJoinFamilyModal = false" class="cancel-btn">取消</button>
          <button @click="joinFamily" class="confirm-btn">加入</button>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.family-container {
  padding: 20px;
  background: #f5f7fa;
  min-height: calc(100vh - 40px);
  box-sizing: border-box;
  width: 100%;
  overflow-x: hidden;
}

.family-content {
  background: white;
  border-radius: 4px;
  padding: 20px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  max-width: 100%;
  box-sizing: border-box;
}

.section {
  margin: 40px 0;
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  width: 100%;
  box-sizing: border-box;
}

.section h2 {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  gap: 10px;
  font-size: 18px;
  color: #333;
  font-weight: 500;
}

.clickable {
  cursor: pointer;
  user-select: none;
}

.clickable:hover {
  opacity: 0.8;
}

.toggle-btn {
  background: none;
  border: none;
  font-size: 16px;
  cursor: pointer;
  color: #333;
  padding: 0;
  margin: 0;
  line-height: 1;
}

.toggle-btn:hover {
  color: #666;
}

.budget-summary-card {
  display: flex;
  gap: 18px;
  margin-bottom: 18px;
  align-items: center;
}

.summary-item {
  flex: 1;
  background: white;
  border-radius: 8px;
  padding: 18px;
  text-align: center;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.summary-item .label {
  font-size: 14px;
  color: #666;
  margin-bottom: 10px;
}

.summary-item .amount {
  font-size: 22px;
  font-weight: bold;
}

.summary-item.total-budget .amount {
  color: #409eff;
}

.budget-list {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.budget-items {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.budget-item {
  background: #f5f7fa;
  border-radius: 4px;
  padding: 16px;
  transition: all 0.3s;
}

.budget-item:hover {
  background: #ecf5ff;
}

.category {
  color: #2c2c2c;
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 8px;
}

.amounts {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 8px;
  font-size: 14px;
}

.amount {
  color: #409eff;
}

.actual-amount {
  font-weight: 500;
}

.percentage {
  color: #909399;
}

.progress-bar {
  width: 100%;
  height: 8px;
  background: #ebeef5;
  border-radius: 4px;
  overflow: hidden;
  margin: 12px 0;
}

.progress {
  height: 100%;
  transition: width 0.3s;
}

.budget-users {
  margin-top: 12px;
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}

.user-budget {
  display: flex;
  align-items: center;
  gap: 8px;
  background: white;
  padding: 4px 12px;
  border-radius: 4px;
  font-size: 14px;
}

.status-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background-color: #67c23a;
  flex-shrink: 0;
}

.status-dot.over-budget {
  background-color: #f56c6c;
}

.username {
  color: #606266;
}

.user-amount {
  color: #909399;
  font-size: 12px;
  margin-left: 4px;
}

.loading, .empty {
  text-align: center;
  color: #909399;
  padding: 20px 0;
}

.search-section {
  background: #f5f7fa;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 24px;
}

.search-inputs {
  display: flex;
  gap: 16px;
  align-items: center;
  flex-wrap: wrap;
}

.input-group {
  flex: 1;
  min-width: 200px;
}

.search-input,
.type-select {
  width: 100%;
  height: 36px;
  padding: 0 12px;
  border: 1px solid #dcdfe6;
  border-radius: 6px;
  font-size: 14px;
  color: #606266;
  transition: all 0.3s;
}

.search-input:focus,
.type-select:focus {
  border-color: #409eff;
  outline: none;
}

.button-group {
  display: flex;
  gap: 12px;
  margin-left: auto;
}

.search-btn,
.reset-btn,
.export-btn {
  display: flex;
  align-items: center;
  gap: 6px;
  height: 36px;
  padding: 0 16px;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s;
}

.search-btn {
  background: #409eff;
  color: white;
}

.search-btn:hover {
  background: #66b1ff;
}

.reset-btn {
  background: #f4f4f5;
  color: #606266;
}

.reset-btn:hover {
  background: #e9e9eb;
}

.export-btn {
  background: #67c23a;
  color: white;
}

.export-btn:hover {
  background: #85ce61;
}

.table-container {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  margin-bottom: 24px;
}

.bill-table {
  width: 100%;
  border-collapse: collapse;
}

.bill-table th,
.bill-table td {
  padding: 16px;
  text-align: left;
  border-bottom: 1px solid #ebeef5;
  font-size: 14px;
  color: #606266;
}

.bill-table th {
  background: #f5f7fa;
  color: #606266;
  font-weight: 500;
}

.bill-table tbody tr:hover {
  background: #f5f7fa;
}

.amount {
  font-weight: 500;
}

.amount.income {
  color: #67c23a;
}

.amount.expense {
  color: #f56c6c;
}

.status-tag {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.status-paid {
  background: #f0f9eb;
  color: #67c23a;
}

.status-unpaid {
  background: #fef0f0;
  color: #f56c6c;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px;
  color: #909399;
  font-size: 14px;
  gap: 12px;
}

.empty-state i {
  font-size: 24px;
}

.pagination {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  gap: 12px;
}

.total-records {
  color: #606266;
  font-size: 14px;
}

.page-size-select {
  height: 32px;
  padding: 0 8px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  font-size: 14px;
  color: #606266;
}

.page-btn {
  padding: 6px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  background: white;
  color: #606266;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s;
}

.page-btn:disabled {
  cursor: not-allowed;
  opacity: 0.6;
}

.page-btn:not(:disabled):hover {
  border-color: #409eff;
  color: #409eff;
}

.page-numbers {
  display: flex;
  gap: 4px;
}

.page-numbers button {
  min-width: 32px;
  height: 32px;
  padding: 0 8px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  background: white;
  color: #606266;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s;
}

.page-numbers button:hover {
  border-color: #409eff;
  color: #409eff;
}

.page-numbers button.active {
  background: #409eff;
  color: white;
  border-color: #409eff;
}

.sortable {
  cursor: pointer;
  user-select: none;
  position: relative;
}

.sortable:hover {
  background-color: #ebeef5;
}

.sort-icon {
  display: inline-flex;
  align-items: center;
  color: #c0c4cc;
  margin-left: 4px;
}

.desc {
  color: #409eff;
  transform: rotate(180deg);
}

.asc {
  color: #409eff;
  transform: rotate(0deg);
}

/* 消息按钮样式 */
.header-container {
  position: sticky;
  top: 0;
  z-index: 100;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.family-info {
  display: flex;
  align-items: center;
}

.family-name {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  display: flex;
  align-items: center;
  gap: 12px;
}

.invite_code {
  font-size: 14px;
  color: #909399;
  font-weight: normal;
  padding-left: 12px;
  border-left: 1px solid #dcdfe6;
}

.action-buttons {
  display: flex;
  gap: 12px;
}

.action-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px 20px;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
}

.message-btn {
  background: #409eff;
  color: white;
}

.message-btn:hover {
  background: #66b1ff;
  transform: translateY(-2px);
}

.user-btn {
  background: #67c23a;
  color: white;
}

.user-btn:hover {
  background: #85ce61;
  transform: translateY(-2px);
}

.action-btn i {
  font-size: 16px;
}

/* 消息弹窗样式 */
.message-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.message-modal-content {
  background: white;
  border-radius: 8px;
  width: 600px;
  max-width: 90%;
  display: flex;
  flex-direction: column;
}

.message-modal-header {
  padding: 20px;
  border-bottom: 1px solid #ebeef5;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.message-modal-header h3 {
  margin: 0;
  font-size: 18px;
  color: #303133;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  color: #909399;
  cursor: pointer;
}

.message-input-container {
  padding: 20px;
  position: relative;
}

.message-textarea {
  width: 100%;
  height: 200px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 16px;
  font-size: 16px;
  line-height: 1.6;
  resize: none;
  outline: none;
}

.message-textarea:focus {
  border-color: #409eff;
}

.message-actions {
  padding: 20px;
  border-top: 1px solid #ebeef5;
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.cancel-btn,
.send-btn {
  padding: 10px 24px;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  border: none;
}

.cancel-btn {
  background: #f4f4f5;
  color: #606266;
}

.send-btn {
  background: #409eff;
  color: white;
}

.cancel-btn:hover {
  background: #e9e9eb;
}

.send-btn:hover {
  background: #66b1ff;
}

/* 用户管理样式 */
.user-management-content {
  padding: 20px;
  max-height: 400px;
  overflow-y: auto;
}

.member-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px;
  border-bottom: 1px solid #ebeef5;
  transition: all 0.3s;
}

.member-item:hover {
  background-color: #f5f7fa;
}

.member-info {
  display: flex;
  align-items: center;
}

.member-name {
  font-size: 16px;
  color: #303133;
  margin-right: 8px;
}

.member-actions {
  display: flex;
  gap: 8px;
}

.action-btn {
  padding: 6px 12px;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  border: none;
}

.demote-btn {
  background: #e6a23c;
  color: white;
}

.demote-btn:hover {
  background: #ebb563;
}

.remove-btn {
  background: #f56c6c;
  color: white;
}

.remove-btn:hover {
  background: #f78989;
}

.invite-btn {
  background: #67c23a;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  margin-right: auto;
}

.invite-btn:hover {
  background: #85ce61;
}

.invite-content {
  padding: 20px;
}

.phone-input-group {
  margin-bottom: 20px;
}

.phone-input {
  width: 100%;
  height: 40px;
  padding: 0 15px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  font-size: 14px;
  transition: all 0.3s;
}

.phone-input:focus {
  border-color: #409eff;
  outline: none;
}

.searching-status {
  text-align: center;
  color: #909399;
  padding: 20px 0;
}

.searched-user {
  background: #f5f7fa;
  border-radius: 4px;
  padding: 15px;
  margin-top: 10px;
}

.user-info {
  display: flex;
  margin-bottom: 10px;
  font-size: 14px;
}

.user-info:last-child {
  margin-bottom: 0;
}

.user-info .label {
  color: #909399;
  width: 70px;
}

.user-info .value {
  color: #303133;
  font-weight: 500;
}

.send-btn:disabled {
  background: #a0cfff;
  cursor: not-allowed;
}

.promote-btn {
  background: #67c23a;
  color: white;
}

.promote-btn:hover {
  background: #85ce61;
}

.permission-tag {
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 12px;
  margin-left: 8px;
}

.creator-tag {
  background-color: #ffd700;
  color: #b8860b;
  border: 1px solid #daa520;
}

.admin-tag {
  background-color: #e1f3d8;
  color: #67c23a;
  border: 1px solid #c2e7b0;
}

.member-tag {
  background-color: #f4f4f5;
  color: #909399;
  border: 1px solid #e9e9eb;
}

.no-family-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 80vh;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.welcome-text {
  text-align: center;
  margin-bottom: 40px;
}

.welcome-text h2 {
  font-size: 24px;
  color: #303133;
  margin-bottom: 12px;
}

.welcome-text p {
  font-size: 16px;
  color: #909399;
}

.action-buttons {
  display: flex;
  gap: 40px;
}

.action-card {
  width: 240px;
  padding: 30px;
  background: #ffffff;
  border-radius: 8px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s;
  border: 1px solid #e4e7ed;
  position: relative;
  overflow: hidden;
}

.action-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  border-color: #409eff;
}

.action-card:hover .card-icon {
  transform: scale(1.1);
}

.action-card:first-child {
  background: linear-gradient(135deg, #ecf5ff 0%, #ffffff 100%);
}

.action-card:last-child {
  background: linear-gradient(135deg, #f0f9eb 0%, #ffffff 100%);
}

.card-icon {
  font-size: 36px;
  margin-bottom: 20px;
  transition: all 0.3s;
}

.action-card:first-child .card-icon {
  color: #409eff;
}

.action-card:last-child .card-icon {
  color: #67c23a;
}

.action-card h3 {
  font-size: 18px;
  color: #303133;
  margin-bottom: 12px;
  position: relative;
}

.action-card p {
  font-size: 14px;
  color: #909399;
  line-height: 1.6;
  margin: 0;
  position: relative;
}

.modal-body {
  padding: 20px;
}

.form-input {
  width: 100%;
  height: 36px;
  padding: 0 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  font-size: 14px;
  box-sizing: border-box;
}

.form-input:focus {
  border-color: #409eff;
  outline: none;
}

.confirm-btn {
  background: #409eff;
  color: white;
  border: none;
  padding: 8px 20px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.confirm-btn:hover {
  background: #66b1ff;
}

.warning-text {
  color: #f56c6c;
  font-size: 14px;
  text-align: center;
  margin: 20px 0;
}

.delete-btn {
  background: #f56c6c;
  color: white;
  border: none;
  padding: 8px 20px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.delete-btn:hover {
  background: #f78989;
}
</style>
